import { history } from '@@/core/history';
import { Button, Form, Input, Checkbox, message, Popover } from 'antd';
import { saveAs } from 'file-saver';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { connect, useDispatch } from 'umi';

import type { Dispatch } from 'umi';

import Andon from '@/assets/images/Andon.svg';
import { getAllDocx } from '@/services/orderManage';
import { getErrorMsg, priceFormat } from '@/util/utils';

export interface Props {
  currentOrder: any;
}

import styles from './index.less';

const USER_INFO = JSON.parse(localStorage.getItem('USER_INFO') as string);
const PurchasedProducts = JSON.parse(localStorage.getItem('PurchasedProducts') as string);
export const PRODCTION_NAME = '芍园云安灯软件服务-';
const Renewal = (props: Props) => {
  const [form] = Form.useForm();
  const [time, setTime] = useState(0);
  const [checked, setChecked] = useState<boolean>(false);
  const [buttonLoading, setButtonLoading] = useState<boolean>(false);
  const [list, setList] = useState<any>(null);
  const selectTime = (times: number) => {
    setTime(times);
  };
  const {} = props;
  const dispatch = useDispatch<Dispatch>();
  function handleOnchange(e: any) {
    console.log(`checked = ${e.target.checked}`);
    setChecked(e.target.checked);
  }

  const getTotalPrice = useMemo((): number => {
    const pricePer = form.getFieldValue('price') && form.getFieldValue('price');
    const yearsPrice = () => {
      if (Number(time) === 2) {
        return Number(time);
      } else if (Number(time) === 3) {
        return Number(time);
      } else {
        return Number(time);
      }
    };
    return Math.round(pricePer * yearsPrice() * form.getFieldValue('productionLineNum'));
  }, [form, time]);

  const getList = () => {
    if (PurchasedProducts) {
      setList(PurchasedProducts);
      form.setFieldsValue({
        orderType: PRODCTION_NAME + PurchasedProducts?.productName,
        companyName: USER_INFO?.companyName,
        phone: USER_INFO?.mobileNo,
        productionLineNum: PurchasedProducts?.buyedProductionLineNumber,
      });
      const value = Number(form.getFieldValue('productionLineNum'));
      if (value >= 1 && value <= 20) {
        form.setFieldsValue({
          price: 1980,
        });
      } else if (value >= 21 && value <= 30) {
        form.setFieldsValue({
          price: 1728,
        });
      } else if (value >= 31 && value <= 40) {
        form.setFieldsValue({
          price: 1584,
        });
      } else if (value >= 41 && value <= 50) {
        form.setFieldsValue({
          price: 1386,
        });
      } else if (value >= 51 && value <= 60) {
        form.setFieldsValue({
          price: 1188,
        });
      } else if (value > 60) {
        form.setFieldsValue({
          price: 990,
        });
      }
    }
  };
  useEffect(() => {
    localStorage.removeItem('CURRENT_ORDER_INFO');
    getList();
  }, []);

  const handleEnter = useCallback(() => {
    if (time === 0) {
      return message.warn('请选择续费年数');
    }
    form.validateFields().then(() => {
      setButtonLoading(true);
      const formData = form.getFieldsValue();
      const createOrderParams = {
        orderType: 2,
        saasProductId: list?.productId,
        unitPrice: Number(formData.price),
        discount: 0,
        // paymentAmount: getTotalPrice,
        paymentAmount: null,
        buyTimes: time,
        buyedProductionLineNumber: Number(formData.productionLineNum),
        buyUserId: '',
        buyTimeUnit: 3,
        companyName: formData.companyName,
        contactNo: formData.phone,
      };
      dispatch({
        type: 'OrderManage/add',
        payload: createOrderParams,
        callback: (res: any) => {
          if (res.code === 200) {
            const formValues = {
              id: res.data.data,
              ...formData,
            };
            localStorage.setItem(
              'CURRENT_ORDER_INFO',
              JSON.stringify({
                ...formValues,
                totalPrice: getTotalPrice,
                payYear: time,
              }),
            );
            setButtonLoading(false);
            window.open('/OrderPay');

          } else {
            message.error(getErrorMsg(res));
            setButtonLoading(false);
          }
        },
      });
    });
    // history.push('OrderPay');

  }, [dispatch, form, getTotalPrice, list?.productId, time]);

  return (
    <>
      <div className={styles.orderPayContent} style={{ background: 'rgb(248, 249, 252)' }}>
        <div className={styles.logo} onClick={() => history.push('/')}>
          <div>
            <img src={Andon} alt="" />{' '}
          </div>
          <div>
            <div className={styles.andon}>Andon</div>
            <div className={styles.sys}>异常快速反应系统</div>
          </div>
        </div>
        <div className={styles.card} style={{ background: 'rgb(248, 249, 252)' }}>
          <div className={styles.content}>
            <div onClick={() => history.push('OrderManage')} className={styles.title}>
              产品服务订单-续费
            </div>
            <Form
              form={form}
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 19 }}
              initialValues={{}}
              autoComplete="off"
            >
              <Form.Item label="订购版本" name="orderType">
                <Input disabled={true} />
              </Form.Item>
              <Form.Item label="价格" name="price">
                <Input disabled={true} />
              </Form.Item>
              <Form.Item
                label="企业全称"
                name="companyName"
              >
                <Input disabled={true} />
              </Form.Item>
              <Form.Item
                label="联系电话"
                name="phone"
                rules={[
                  { required: true, message: '请输入联系电话!' },
                  { pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/, message: '请输入正确的手机号' },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item label="产线数量" name="productionLineNum">
                <Input disabled={true} />
              </Form.Item>
              <Form.Item label="续费期限">
                <div className={styles.renewalTime}>
                  <div
                    style={
                      time === 1
                        ? { background: 'rgba(47, 80, 212, 0.02)', border: '1px solid #2F50D4' }
                        : {}
                    }
                    onClick={() => selectTime(1)}
                    className={styles.time}
                  >
                    <span>1年</span>
                  </div>
                  <div
                    style={
                      time === 2
                        ? { background: 'rgba(47, 80, 212, 0.02)', border: '1px solid #2F50D4' }
                        : {}
                    }
                    onClick={() => selectTime(2)}
                    className={styles.time}
                  >
                    {/*<div>9.8折</div>*/}
                    <span>2年</span>
                  </div>
                  <div
                    style={
                      time === 3
                        ? { background: 'rgba(47, 80, 212, 0.02)', border: '1px solid #2F50D4' }
                        : {}
                    }
                    onClick={() => selectTime(3)}
                    className={styles.time}
                  >
                    {/*<div style={{ background: '#EF4859' }}>8.8折</div>*/}
                    <span>3年</span>
                  </div>
                </div>
              </Form.Item>
              {/*<Form.Item label={'续费服务时间：'}>*/}
              {/*  <div> 2022年6月17日~ 2023年6月16日</div>*/}
              {/*</Form.Item>*/}
            </Form>
          </div>
          <div className={styles.bottomContent}>
            <div className={styles.orderMoney}>
              订单金额 <span>￥{priceFormat((getTotalPrice))==='NaN.00' ? 0.00 : priceFormat((getTotalPrice))}</span>
            </div>
            <div className={styles.des}>提交订单后可申请合同、开具发票</div>
            <div className={styles.agreeAndButton}>
              <Checkbox onChange={handleOnchange} />
              &nbsp; &nbsp;同意&nbsp; &nbsp;
              <Popover content={(<div style={{ cursor: 'pointer', color: '#1a3dc9' }} onClick={async () => {
                const res = await getAllDocx(2);
                if (res.code===200) {
                  const fileType = (res.data.path).split('.')[1];
                  saveAs('images/' + res.data.path, `芍园云软件付费服务协议.${fileType}`);
                } else {
                  message.error('下载错误！');
                }
              }}>芍园云软件付费服务协议</div>)} title="下载条款">
                <span  onClick={() => window.open('Agreement?id=2')} className={styles.safe}>芍园云软件付费服务协议</span>
              </Popover>
              <Button loading={buttonLoading} type={'primary'} disabled={!checked} onClick={() => handleEnter()}>
                提交订单
              </Button>
            </div>
          </div>
        </div>
      </div>

    </>
  );
};
const mapState = (state: any) => {
  return {
    currentOrder: state.OrderManage.currentOrder,
  };
};
export default connect(mapState)(Renewal);
